package com.pig4cloud.pig.admin.rocketMQ;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

@Component
public class RocketMQProducer {

		@Value("${rocketmq.name-server}")
		private String nameServer;

		@Value("${rocketmq.producer.group}")
		private String producerGroup;

		public void sendMessage(String topic, String message) throws MQClientException, RemotingException, InterruptedException, MQBrokerException, UnsupportedEncodingException {
			DefaultMQProducer producer = new DefaultMQProducer(producerGroup);
			producer.setNamesrvAddr(nameServer);
			producer.start();

			Message msg = new Message(topic, String.valueOf(0), message.getBytes(RemotingHelper.DEFAULT_CHARSET));
			producer.send(msg);

			producer.shutdown();
		}
}
